package com.etung.iot.demo.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etung.iot.demo.configs.MqttConfig;
import com.etung.iot.demo.vo.req.AccessRequest;
import com.etung.iot.demo.vo.resp.DeviceAccessInfo;
import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.dao.AccessInfoMapper;
import com.etung.iot.demo.modles.AccessInfo;
import com.etung.iot.demo.services.AccessService;
import com.etung.iot.demo.utils.AppUtil;
import com.etung.iot.demo.utils.TopicUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Slf4j
public class AccessServiceImpl implements AccessService {
    @Autowired
    private AccessInfoMapper accessInfoMapper;

    @Autowired
    private MqttConfig mqttConfig;


    @Transactional
    @Override
    public DeviceAccessInfo genAccessInfo(AccessRequest accessRequest) {
        DeviceAccessInfo deviceAccessInfo = new DeviceAccessInfo();
        try {
            String productKey = accessRequest.getProductKey();
            String imei = accessRequest.getImei();
            if (StringUtils.isEmpty(productKey)) {
                genAccessInfo(imei, deviceAccessInfo);
            } else {
                AccessInfo accessInfo = accessInfoMapper.selectOne(new QueryWrapper<AccessInfo>().eq("product_key", productKey).eq("device_name", imei));
                if (accessInfo != null) {
                    deviceAccessInfo.setProductKey(productKey);
                    deviceAccessInfo.setDeviceSecret(accessInfo.getDeviceSecret());
                } else {
                    genAccessInfo(imei, deviceAccessInfo);
                }
            }
            productKey = deviceAccessInfo.getProductKey();
            deviceAccessInfo.setDeviceName(imei);
            deviceAccessInfo.setRealDataTopic(TopicUtil.replaceGenPath(TopicConfig.REAL_DATA_TOPIC, productKey, imei));
            deviceAccessInfo.setPlcStatusTopic(TopicUtil.replaceGenPath(TopicConfig.PLC_STATUS_TOPIC, productKey, imei));
            deviceAccessInfo.setGatewayInfoTopic(TopicUtil.replaceGenPath(TopicConfig.COLLECTOR_INFO_TOPIC, productKey, imei));
            deviceAccessInfo.setAlarmPushTopic(TopicUtil.replaceGenPath(TopicConfig.ALARM_INFO_TOPIC, productKey, imei));
            deviceAccessInfo.setVarControlTopic(TopicUtil.replaceGenPath(TopicConfig.VARIANT_CONTROL_TOPIC, productKey, imei));
            deviceAccessInfo.setVarControlReplyTopic(TopicUtil.replaceGenPath(TopicConfig.VARIANT_REPLY_TOPIC, productKey, imei));
            deviceAccessInfo.setRemoteDownloadConfigTopic(TopicUtil.replaceGenPath(TopicConfig.DOWNLOAD_TOPIC, productKey, imei));
            deviceAccessInfo.setRemoteDownloadConfigReplyTopic(TopicUtil.replaceGenPath(TopicConfig.DOWNLOAD_REPLY_TOPIC, productKey, imei));
            deviceAccessInfo.setRemoteUpdateTopic(TopicUtil.replaceGenPath(TopicConfig.REMOTE_UPDATE_TOPIC, productKey, imei));
            deviceAccessInfo.setRemoteUpdateReplyTopic(TopicUtil.replaceGenPath(TopicConfig.REMOTE_UPDATE_REPLY_TOPIC, productKey, imei));
            deviceAccessInfo.setTimeSynTopic(TopicUtil.replaceGenPath(TopicConfig.TIME_SYNS_TOPIC, productKey, imei));
            String hostUrl = mqttConfig.getHostUrl();
            String[] parts = hostUrl.split("//");
            if (parts.length == 2) {
                String[] ipInfo = parts[1].split(":");
                deviceAccessInfo.setServerAddress(ipInfo[0]);
                deviceAccessInfo.setServerPort(ipInfo[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceAccessInfo;
    }

    private void genAccessInfo(String imei, DeviceAccessInfo deviceAccessInfo) {
        //清除以前的访问信息
        accessInfoMapper.delete(new LambdaQueryWrapper<AccessInfo>().eq(AccessInfo::getDeviceName, imei));
        //生成新的访问信息
        String productKey = AppUtil.getAppId();
        String deviceSecret = AppUtil.getAppSecret(productKey);
        AccessInfo accessInfo = new AccessInfo();
        accessInfo.setProductKey(productKey).setDeviceName(imei).setDeviceSecret(deviceSecret).setCreateTime(new Date());
        accessInfoMapper.insert(accessInfo);
        deviceAccessInfo.setDeviceSecret(deviceSecret);
        deviceAccessInfo.setProductKey(productKey);
    }
}
